package cringer::translate;

# translate.pm
# provides translation functionality for cringer

use JSON;

our $VERSION = '2.0';

our $defaultLanguage = 'en'; # default language (i.e., everything will be translated to this unless instructed otherwise)
our $reliabilityThreshold = .25; # threshold above which we'll trust the language detect and proceed with the translation.


sub said{
 my $self = $_[0];
 my $args = $_[1];
 my $me = $self->{nick};
 
 my $srcLang = undef; # start out assuming we have to detect language
 if($args->{body} =~ s/^([^:]+)(?=->[^:]+:)//){ # check for a user-specified source language
  $srcLang = $1;
 }
 my $destLang = $defaultLanguage; # start out assuming default language
 if($args->{body} =~ s/^->([^:]+)://){ # check for a user-specified destination language
  $destLang = $1;
 }

 unless($args->{body} =~ /\S+\s+\S+\s+\S+/i){ # If there's not going to be enough to translate, we'll just skip it
  return;
 }
 
 my $baseUrl = qq~http://ajax.googleapis.com/ajax/services/language/~;
 
 # first, we check the language

 my $confidence;
 if(!defined($srcLang)){
  my $dUrl = $baseUrl . qq~detect?v=1.0&q=~ . cringer::uriencode($args->{body});
  my $r = $self->{ua}->get($dUrl);
  my $json;
  eval { $json = from_json($r->decoded_content); };
  if(($@ ne '') || (defined($json->{responseData}->{error}))){
   print qq~\n================\Lang Detect error:\n~ . $r->decoded_content . qq~\nError: $@\n================\n~;
   return;
  }
  if($json->{responseData}->{confidence} > $reliabilityThreshold){
   $srcLang = $json->{responseData}->{language};
   $confidence = $json->{responseData}->{confidence};
  } else {
   return;
  }
 }
 
 if(($srcLang eq $destLang) || ($srcLang eq '')){
  return;
 }

 my $tUrl = $baseUrl . qq~translate?v=1.0&format=text&langpair=~.cringer::uriencode(join('|',($srcLang,$destLang))).qq~&q=~.cringer::uriencode($args->{body});
 my $r = $self->{ua}->get($tUrl);
 my $json;
 eval { $json = from_json($r->decoded_content); };
 if(($@ ne '') || (defined($json->{responseData}->{error}))){
  print qq~================\Translate error:\n~ . $r->decoded_content . qq~\nError: $@\n================\n~;
  return;
 }
 if($json->{responseStatus} == 200){
  return qq~\~$args->{who} (~ . join('|',((defined($srcLang)) ? $srcLang : $json->{responseData}->{detectedSourceLanguage},$destLang)) . ((defined($confidence)) ? qq~ ~ . sprintf("%.2f", $confidence*100) . qq~\%~ : '') . qq~) -> $json->{responseData}->{translatedText}~;
 }
 return;
}


sub commandList{ # a simple help routine to return a list of the commands we'll respond to
 return qq~[srcLang?]->[destLang?]: [stringToTranslate]~;
}


return 1;